/*
 * Author: Karthic Kumar Sekar [A0092622]
 */

package sg.edu.nus.iss.team4ft.service;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;

import sg.edu.nus.iss.team4ft.exception.InvalidOperationException;
import sg.edu.nus.iss.team4ft.util.AppConstant;

public class CableTv extends Plan implements UsageChargable , Serializable {
	
	private static final long serialVersionUID = 1L;

	protected CableTv (CableTv cableTv){
		super(cableTv);
	}
	
	public CableTv (Date startDate) throws InvalidOperationException, IOException{
		super(startDate, PlanCode.CableTV);
		super.setServiceName(AppConstant.CABLE_TV_FEATURE);
		
		//Fill the feature list with default features.
		for(int i =0; i<3; i++){
			Channel c = new Channel(AppConstant.CHANNEL_NAMES[i],startDate, this);
			c.setIsDefaultService(true);
			subscripeNewFeature(c);
		}
			
		Double d = 0.0;
		try {
			d = new RateTable().getSubscriptionCharge(getPlanCode(), FeatureCode.ChannelService);
		} catch (IOException e) {
			e.printStackTrace();
		}
		setSubscriptionCharge(d);
	}

	//Calculate monthly usage charge for the plan based on all the active features
	@Override
	public Double calculateMonthlyUsage(Date forDate) {
		double d = 0.0;
		try {
			for (Feature f : getFeatures()) {
				boolean isDefault = false;
				for (String s : AppConstant.DEFAULT_CHANNEL_NAMES) {
					if(f.getServiceName().equals(s))
						isDefault = true;
				}
				
				if(!isDefault && f.isSubscriptionActive(forDate))
					d = d + f.getChargePerUnit();			
			}
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
			return null;
		}
		return d;
	}
	
	@Override
	public void subscripeNewFeature(Feature feature)
			throws InvalidOperationException {
		//DigitalVoice will allow only feature of following type
		if(feature.getFeatureCode() == FeatureCode.ChannelService)
			super.subscripeNewFeature(feature);
		else
			throw new InvalidOperationException("Feature '" + feature.getFeatureCode().toString() + "' cannot be added to plan'"+ this.getPlanCode().toString() + "'");
	}
		
	@Override
	public Feature getFeature(String featureName) throws CloneNotSupportedException {
		for (Feature f : getFeatures()) {
			if(f.getServiceName().equals(featureName))
				return f.clone();
		}
		return null;
	}

	@Override
	public CableTv clone() throws CloneNotSupportedException {
		return new CableTv(this);
	}
	
}
